from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from app import crud, schemas
from app.database import get_db
from app.api.auth import get_current_user
from app.schemas.user import UserInDB
from app.schemas.comment import CommentCreate, CommentUpdate, CommentResponse

router = APIRouter()

# 获取实体的评论列表
@router.get("/{entity_type}/{entity_id}", response_model=List[CommentResponse])
def get_comments(
    entity_type: str,
    entity_id: int,
    db: Session = Depends(get_db)
):
    """获取指定实体的评论列表"""
    try:
        # 获取评论和作者信息
        comments_with_authors = crud.comment.comment.get_comments_with_authors(db, entity_type, entity_id)
        
        # 构建评论树（支持多级评论）
        comment_dict = {}
        root_comments = []
        
        for comment, author in comments_with_authors:
            comment_data = CommentResponse(
                id=comment.id,
                content=comment.content,
                entity_type=comment.entity_type,
                entity_id=comment.entity_id,
                parent_id=comment.parent_id,
                author_id=comment.author_id,
                author_username=author.username,
                created_at=comment.created_at,
                updated_at=comment.updated_at,
                replies=[]
            )
            comment_dict[comment.id] = comment_data
            
            if comment.parent_id is None:
                root_comments.append(comment_data)
        
        # 构建回复关系
        for comment, author in comments_with_authors:
            if comment.parent_id and comment.parent_id in comment_dict:
                comment_dict[comment.parent_id].replies.append(comment_dict[comment.id])
        
        return root_comments
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取评论失败: {str(e)}"
        )

# 创建评论
@router.post("/{entity_type}/{entity_id}", response_model=CommentResponse, status_code=status.HTTP_201_CREATED)
def create_comment(
    entity_type: str,
    entity_id: int,
    comment: CommentCreate,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    """创建新评论"""
    try:
        # 验证实体是否存在（根据entity_type进行验证）
        if entity_type == "issue":
            entity = crud.issue.get_issue(db, issue_id=entity_id)
            if not entity:
                raise HTTPException(status_code=404, detail="Issue not found")
        elif entity_type == "case":
            entity = crud.case.get_case(db, case_id=entity_id)
            if not entity:
                raise HTTPException(status_code=404, detail="Case not found")
        
        # 如果有parent_id，验证父评论是否存在
        if comment.parent_id:
            parent_comment = crud.comment.comment.get_comment(db, comment.parent_id)
            if not parent_comment:
                raise HTTPException(status_code=404, detail="Parent comment not found")
            if parent_comment.entity_type != entity_type or parent_comment.entity_id != entity_id:
                raise HTTPException(status_code=400, detail="Parent comment does not belong to this entity")
        
        # 创建评论
        created_comment = crud.comment.comment.create_comment(
            db=db, 
            comment=comment, 
            author_id=current_user.id,
            entity_type=entity_type,
            entity_id=entity_id
        )
        
        # 返回包含作者信息的响应
        return CommentResponse(
            id=created_comment.id,
            content=created_comment.content,
            entity_type=created_comment.entity_type,
            entity_id=created_comment.entity_id,
            parent_id=created_comment.parent_id,
            author_id=created_comment.author_id,
            author_username=current_user.username,
            created_at=created_comment.created_at,
            updated_at=created_comment.updated_at,
            replies=[]
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建评论失败: {str(e)}"
        )

# 更新评论
@router.put("/{comment_id}", response_model=CommentResponse)
def update_comment(
    comment_id: int,
    comment_update: CommentUpdate,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    """更新评论（只有作者可以更新）"""
    try:
        # 获取评论
        existing_comment = crud.comment.comment.get_comment(db, comment_id)
        if not existing_comment:
            raise HTTPException(status_code=404, detail="Comment not found")
        
        # 权限检查：只有作者可以更新评论
        if existing_comment.author_id != current_user.id:
            raise HTTPException(status_code=403, detail="Permission denied")
        
        # 更新评论
        updated_comment = crud.comment.comment.update_comment(db, comment_id=comment_id, comment_update=comment_update)
        
        # 返回包含作者信息的响应
        return CommentResponse(
            id=updated_comment.id,
            content=updated_comment.content,
            entity_type=updated_comment.entity_type,
            entity_id=updated_comment.entity_id,
            parent_id=updated_comment.parent_id,
            author_id=updated_comment.author_id,
            author_username=current_user.username,
            created_at=updated_comment.created_at,
            updated_at=updated_comment.updated_at,
            replies=[]
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新评论失败: {str(e)}"
        )

# 删除评论
@router.delete("/{comment_id}", response_model=CommentResponse)
def delete_comment(
    comment_id: int,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    """删除评论（只有作者可以删除）"""
    try:
        # 获取评论
        existing_comment = crud.comment.comment.get_comment(db, comment_id)
        if not existing_comment:
            raise HTTPException(status_code=404, detail="Comment not found")
        
        # 权限检查：只有作者可以删除评论
        if existing_comment.author_id != current_user.id:
            raise HTTPException(status_code=403, detail="Permission denied")
        
        # 删除评论
        deleted_comment = crud.comment.comment.delete_comment(db, comment_id)
        
        # 返回包含作者信息的响应
        return CommentResponse(
            id=deleted_comment.id,
            content=deleted_comment.content,
            entity_type=deleted_comment.entity_type,
            entity_id=deleted_comment.entity_id,
            parent_id=deleted_comment.parent_id,
            author_id=deleted_comment.author_id,
            author_username=current_user.username,
            created_at=deleted_comment.created_at,
            updated_at=deleted_comment.updated_at,
            replies=[]
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除评论失败: {str(e)}"
        )